const { BrowserWindow, app } = require('electron')
const { getMainWindow } = require('ee-core/electron');
const {join} = require("path");

class DownloadController {

    /**
     * 下载文件
     */
    async downloadFile(config) {
        const {files} = config
        console.log('下载数量：', files.length)
        const mainWindow = getMainWindow()

        // 使用动态 import() ，可以在 CommonJS 模块中正确地加载 ES 模块
        const { download } = await import('electron-dl');

        // const files = [
        //     { url: 'http://sns-webpic-qc.xhscdn.com/202502252130/402ef579512100b2ad263c9a31affd7a/1040g00831b264ffi6q0g4a5ftvhn1l6jgk9ae5o!nd_dft_wlteh_webp_3', directory: 'kkk/file1' },
        //     { url: 'http://sns-webpic-qc.xhscdn.com/202502252130/402ef579512100b2ad263c9a31affd7a/1040g00831b264ffi6q0g4a5ftvhn1l6jgk9ae5o!nd_dft_wlteh_webp_3', directory: 'kkk/file2' },
        // ];

        let downloadSucceedList = []
        try {
            for (const file of files) {
                const options = {
                    // directory: join(app.getPath('downloads'), file.directory),
                    directory: file.directory
                };
                try {
                    const dl = await download(mainWindow, file.url, options);
                    console.log(`文件保存到: ${dl.getSavePath()}`);
                    downloadSucceedList.push(dl.getSavePath())
                    mainWindow.webContents.send('controller/download/downloadFile/progress', {list: downloadSucceedList});
                } catch (error) {
                    console.error('文件下载失败：', error);
                }
            }
        } catch (e) {
            console.log('下载出错：', e)
        }
    }
}

DownloadController.toString = () => '[class DownloadController]'
module.exports = DownloadController